export function splitDetail(detail) {
  try {
    const rows = detail.split('\n');
    return rows.reduce((acc, row) => {
      let [key, value] = row.split('：');
      key = key.trim();
      if(key) {
        acc[key] = value.trim();
      }
      return acc;
    },{});
  }catch (err){
    throw new Error(`格式化失败, detail:${detail}, error: ${err}`);
  }
}

export function flattenMenu(menu) {
  return menu.categories.reduce((acc, category) => {
    const products = category.subCategories.flatMap(subCategory => subCategory.products);
    acc.push(...products);
    return acc;
  }, []);
}

export function matchMenuProducts(menuProducts, orderProducts) {
  const failMatchProductNames = [];
  const matchProducts = [];
  orderProducts.forEach(v => {
    const cur = menuProducts.find(p => p.name === v.name);
    if(cur) {
      matchProducts.push({
        ...cur,
        qty: v.qty,
      });
    }else {
      failMatchProductNames.push(v.name);
    }
  });
  if(failMatchProductNames.length > 0){
    throw new Error(`菜单匹配失败，未找到下面商品${failMatchProductNames.join(',')}`)
  }
  return matchProducts;
}

export function getProductPayload(product, orderProduct) {
  const customizationStr = orderProduct.productDescription;
  console.log(`根据选项-${customizationStr}-获取提交数据`);

  let [cupSizeStr, temperatureStr, coffeeTypeStr, milkStr] = getCustomization(customizationStr);

  const { customization_data, coffee_sku_mapping } = product;
  const { specification_list, customizations } = customization_data;
  const cupSizeItem = customizations.find(v => v.name === '杯型');
  const temperatureItem = customizations.find(v => v.name === '温度');
  const milkItem = customizations.find(v => v.name === '添加或更换牛奶');

  if(cupSizeItem) {
    const curOpt = cupSizeItem.extra_list.find(item => item.name === cupSizeStr);
    if(curOpt) {
      curOpt.selected = true;
    }else {
      throw new Error(`杯型匹配失败-${customizationStr}-${JSON.stringify(cupSizeItem)}`)
    }
  }
  if(temperatureItem) {
    const curOpt = temperatureItem.extra_list.find(item => item.name === temperatureStr);
    if(curOpt) {
      curOpt.selected = true;
    }else {
      throw new Error(`温度匹配失败-${customizationStr}-${JSON.stringify(cupSizeItem)}`)
    }
  }

  if(milkItem && milkStr) {
    const curMilk = milkItem.extra_list.find(item => item.name === milkStr);
    if(curMilk) {
      curMilk.selected = true;
    }else {
      throw new Error(`牛奶选项匹配失败-${customizationStr}-${JSON.stringify(milkItem)}`)
    }
  }

  const coffeeSkuKey = specification_list.map(specificationCode => {
    const current = customizations.find(v => v.specification_code === specificationCode);
    const extra_list = current.extra_list;
    const selectedItem = extra_list.find(v => v.selected) || extra_list.find(v => v.is_default === 1);
    if(!selectedItem) {
      throw new Error(`获取 coffee_sku_mapping 选项失败， ${specificationCode} 不匹配`)
    }
    return selectedItem.attribute;
  }).join('_');

  const currentSku = coffee_sku_mapping[coffeeSkuKey];

  if(!currentSku) {
    throw new Error(`获取商品sku失败, ${customizationStr}-${specification_list}-${coffeeSkuKey}-${JSON.stringify(coffee_sku_mapping)}`)
  }

  const add_extra = []
  customizations.forEach(customizationItem => {
    customizationItem.extra_list.forEach(opt => {

      if(opt.selected) {
        // 温热和热 attribute 相同 ,
        if(!customizationItem.specification_code || opt.attribute !== opt.code) {
          add_extra.push({
            id: opt.id,
            extra_sku: opt.code,
            extra_sku_attribute: opt.attribute,
            name: opt.name,
            qty: opt.count || 1,
          });
        }
      }
    })
  })


  const selectedCupSizeItem = cupSizeItem.extra_list.find(v => v.selected);

  const productData = {
    name: customization_data.name,
    image: customization_data.default_image,
    id: customization_data.id,
    spec_id: currentSku.id,
    sku: customization_data.code,
    spec_sku: currentSku.sku_id,
    cupSize: selectedCupSizeItem.name,
    customizationStr: customizationStr,
    customizePrice: "0.00",
    add_extra,
    markPrice: currentSku.price
  }

  console.log(`${customization_data.name}(${customizationStr})-获取提交数据成功:${JSON.stringify(productData)}`)

  return productData
}


function getCustomization(customizationStr) {
  const customizationList = customizationStr.split(',');
  const cupSizeStr = customizationList[0].replace('双', '');
  const temperatureStr = customizationList[1];

  let coffeeTypeStr = '';
  let milkStr = '';

  if(customizationList.length === 4) {
    coffeeTypeStr = customizationList[2];
    milkStr = customizationList[3];
  }else if(customizationList.length === 3) {
    const lastItem = customizationList[customizationList.length - 1];
    if(lastItem.includes('奶')) {
      milkStr = lastItem;
    }else {
      coffeeTypeStr = lastItem;
    }
  }
  return [cupSizeStr, temperatureStr, coffeeTypeStr, milkStr]
}
